﻿/// <reference path="../../extjs/ext-all-debug.js" />
Ext.define('yzmh.controller.Chapters', {
    extend: 'Ext.app.Controller',

    stores: ['Comics', 'Chapters', 'ComicDatas', 'Downloads'],

    models: ['Comic', 'Chapter'],

    views: ['comic.List', 'chapter.List', 'chapter.Edit', 'chapter.EditMulti'],

    refs: [{
        ref: 'grid',
        selector: 'chapterlist'
    },{
        ref: 'tbar',
        selector: 'chapterlist toolbar'
    }, {
        ref: 'progressbar',
        selector: 'chapterlist progressbar'
    }, {
        ref: 'statusbar',
        selector: 'chapterlist statusbar'
    }],

    init: function () {
        this.control({
            'comiclist': {
                itemdblclick: this.showChapter
            },
            'chapterlist': {
                render: this.renderChapterList,
                itemdblclick: this.showChapterPictures
            },
            'chapterlist dataview': {
                drop: this.sortChapter
            },
            'chapterlist actioncolumn[action=edit]': {
                click: this.editChapter
            },
            'chapterlist actioncolumn[action=view]': {
                click: this.viewChapter
            },
            'chapterlist button[action=delete]': {
                click: this.deleteChapter
            },
            'chapterlist button[action=add] menuitem': {
                click: this.addChapter
            },
            'chapterlist button[action=html]': {
                click: this.htmlChapter
            },
            'chapterlist button[action=htmlall]': {
                click: this.htmlAllChapter
            },
            'chapterlist button[action=download]': {
                click: this.downloadChapter
            },
            'chapterlist button[action=rename]': {
                click: this.renameChapter
            },
            'chapterlist button[action=refresh]': {
                click: this.refresh
            },
            'chapterlist button[action=editmulti]': {
                click: this.editMulti
            },
            'chapteredit button[action=save]': {
                click: this.saveChapter
            },
            'chapteredit textareafield': {
                change: this.getTps
            },
            'chaptereditmulti button[action=save]': {
                click: this.saveMulti
            }
        });
    },

    saveMulti: function (button) {
        var win = button.up('window'),
            form = win.down('form'),
            store = Ext.ComponentQuery.query("tabpanel")[0].getActiveTab().getStore() || this.getChaptersStore();
        if (form.getForm().isValid()) {
            form.submit({
                clientValidation: true,
                waitMsg: '正在提交数据...',
                url: 'data/chapter.aspx?a=savemulti',
                success: function (form, action) {
                    win.close();
                    store.reload();
                },
                failure: function (form, action) {
                    Ext.Msg.alert('失败', action.result ? action.result.errorMessage : 'No response');
                }
            });
        }
    },

    editMulti: function (button) {
        var rows = this.getGrid().getSelectionModel().getSelection();
        if (rows.length > 0) {
            var ids = [];
            Ext.each(rows, function (row) {
                ids.push(row.get('id'));
            });
            var edit = Ext.create('yzmh.view.chapter.EditMulti').show();
            edit.down("hidden[name=ids]").setValue(ids.join(','));
        }
    },

    getTps: function (field, newValue, oldValue) {
        field.up('form').down('numberfield').setValue(newValue.split('|').length);
    },

    downloadChapter: function (button) {
        var rows = this.getGrid().getSelectionModel().getSelection();
        if (rows.length > 0) {
            var store = this.getChaptersStore();
            var zjid = [];
            Ext.each(rows, function (r) {
                zjid.push(r.get("id"));
            });
            Ext.Ajax.request({
                url: 'data/chapter.aspx?a=download',
                params: { zjid: zjid.join(',') },
                method: 'POST',
                success: function (response, opts) {
                    var result = Ext.decode(response.responseText);
                    if (result.success) {
                        notification('提示' ,rows.length + "章漫画已加入下载列表");
                    } else {
                        notification('错误', result.errorMessage, true);
                    }
                }
            });
        }
    },

    renameChapter: function (button) {
        var rows = this.getGrid().getSelectionModel().getSelection(), store = this.getChaptersStore();
        if (rows.length > 0) {
            var store = this.getChaptersStore();
            var zjid = [];
            Ext.each(rows, function (r) {
                zjid.push(r.get("id"));
            });
            Ext.Ajax.request({
                url: 'data/chapter.aspx?a=rename',
                params: { zjid: zjid.join(',') },
                method: 'POST',
                success: function (response, opts) {
                    var result = Ext.decode(response.responseText);
                    if (result.success) {
                        notification('提示', rows.length + "已重命名成功");
                        store.reload();
                    } else {
                        notification('错误', result.errorMessage, true);
                    }
                }
            });
        }
    },

    refresh: function (button) {
        this.getChaptersStore().reload();
    },

    sortChapter:function (node, data, dropRec, dropPosition) {
        var ordernum = [],  store = this.getChaptersStore(), grid = this.getGrid();
        grid.mask();
        store.each(function (record) {
            ordernum.push(record.get('ordernum'));
        });
        ordernum.sort(function (a, b) { return b - a; });
        var data = [];
        store.each(function (record, i) {
            if (ordernum[i] != record.get('ordernum')) {
                record.set("ordernum", ordernum[i]);
                data.push({
                    id: record.get('id'),
                    ordernum: record.get('ordernum')
                });
                
            }
        });
        Ext.Ajax.request({
            url: 'data/chapter.aspx?a=sort',
            params: { data: Ext.encode(data) },
            method: 'POST',
            success: function (response, opts) {
                grid.unmask();
                var result = Ext.decode(response.responseText);
                if (!result.success) {
                    notification("错误", result.errorMessage, true);
                    store.reload();
                }
            }
        });
    },

    showChapterPictures: function (grid, record) {
        Ext.Ajax.request({
            url: 'data/chapter.aspx?a=cookie',
            params: { tpadd: record.get('tpadd') },
            method: 'POST',
            success: function (response, opts) {
                var result = Ext.decode(response.responseText);
                if (result.success) {
                    var finder = new CKFinder();
                    finder.startupPath = Ext.util.Cookies.get("CKFinder:DynamicBaseUrl") + ':/' + decodeURI(record.get('tpadd'));
                    finder.basePath = '../';
                    finder.selectActionFunction = null;
                    finder.selectActionData = null;
                    finder.selectThumbnailActionFunction = null;
                    finder.popup();
                } else {
                    Ext.Msg.alert("错误", result.errorMessage);
                }
            }
        });
    },

    addChapter: function (button) {
        Ext.util.Cookies.set("CKFinder:DynamicBaseUrl", button.text);
        var edit = Ext.create('yzmh.view.chapter.Edit').show();
        edit.down("hidden[name=cid]").setValue(button.up('grid').comicid);
    },

    saveChapter: function (button) {
        var win = button.up('window'),
            form = win.down('form'),
            record = form.getRecord(),
            values = form.getValues(),
            store = Ext.ComponentQuery.query("tabpanel")[0].getActiveTab().getStore() || this.getChaptersStore();//[this.getChaptersStore(), this.getDownloadsStore()];
        if (form.getForm().isValid()) {
            form.submit({
                clientValidation: true,
                waitMsg: '正在提交数据...',
                url: 'data/chapter.aspx?a=save',
                success: function (form, action) {
                    win.close();
                    store.reload();
                },
                failure: function (form, action) {
                    Ext.Msg.alert('失败', action.result ? action.result.errorMessage : 'No response');
                }
            });
        }
    },

    showChapter: function (grid, record) {
        var tab = grid.up("viewport").down('tabpanel');
        var p = tab.down('chapterlist');
        if (p != null) {
            tab.remove(p);
        }
        p = tab.add({
            xtype: 'chapterlist',
            title: record.get('mhmc') + "章节列表",
            icon: 'extjs/icons/book.png',
            comicid: record.get('id')
        });
        tab.setActiveTab(p);
    },

    viewChapter: function (o, item, rowIndex, colIndex, e, row) {
        window.open("/comic/" + o.up("grid").comicid + "/" + row.get('id') + ".html", '_blank');
    },

    editChapter: function (o, item, rowIndex, colIndex, e, row) {
        Ext.Ajax.request({
            url: 'data/chapter.aspx?a=cookie',
            params: { tpadd: row.get('tpadd') },
            method: 'POST',
            success: function (response, opts) {
                var result = Ext.decode(response.responseText);
                if (result.success) {
                    var edit = Ext.create('yzmh.view.chapter.Edit').show();
                    edit.down('form').loadRecord(row);
                } else {
                    Ext.Msg.alert("错误", result.errorMessage);
                }
            }
        });
    },

    deleteChapter: function () {
        var rows = this.getGrid().getSelectionModel().getSelection();
        if (rows.length == 0) {
            Ext.Msg.alert("提示", "请至少选择一行记录！");
            return;
        }
        var store = this.getChaptersStore();
        var ids = [];
        Ext.each(rows, function (r) {
            ids.push(r.get("id"));
        });
        Ext.Msg.confirm("提示", "确定要删除选中的" + rows.length + "个章节吗？", function (result) {
            if (result == "yes") {
                Ext.Ajax.request({
                    url: 'data/chapter.aspx?a=delete',
                    params: { ids: ids.join(',') },
                    method: 'POST',
                    success: function (response, opts) {
                        var result = Ext.decode(response.responseText);
                        if (result.success) {
                            store.remove(rows);
                        } else {
                            Ext.Msg.alert("错误", result.errorMessage);
                        }
                    }
                });
            }
        });
    },

    htmlChapter: function () {
        var rows = this.getGrid().getSelectionModel().getSelection();
        if (rows.length == 0) {
            Ext.Msg.alert("提示", "请至少选择一行记录！");
            return;
        }
        var store = this.getChaptersStore();
        var pbar = this.getProgressbar();
        var v = 0;
        function createZJ(record) {
            Ext.Ajax.request({
                url: 'data/makehtml.aspx?a=zj',
                params: { id: record.get("id") },
                method: 'POST',
                success: function (response, opts) {
                    var result = Ext.decode(response.responseText);
                    if (result.success) {
                        v++;
                        pbar.updateProgress(v / rows.length, '生成HTML页面 ' + v + ' / ' + rows.length + '...');
                        if (rows[v] != null) {
                            createZJ(rows[v]);
                        } else {
                            pbar.updateText('生成HTML完成')
                        }
                    } else {
                        Ext.Msg.alert("错误", result.errorMessage);
                    }
                }
            });
        }
        Ext.Msg.confirm("提示", "确定要生成选中的" + rows.length + "个章节吗？", function (result) {
            if (result == "yes") {
                pbar.reset();
                pbar.show();
                createZJ(rows[0])
            }
        });
    },

    htmlAllChapter: function () {
        var rows = [];
        var store = this.getChaptersStore();
        var pbar = this.getProgressbar();
        var v = 0;
        function createZJ(id) {
            Ext.Ajax.request({
                url: 'data/makehtml.aspx?a=zj',
                params: { id: id },
                method: 'POST',
                success: function (response, opts) {
                    var result = Ext.decode(response.responseText);
                    if (result.success) {
                        v++;
                        pbar.updateProgress(v / rows.length, '生成HTML页面 ' + v + ' / ' + rows.length + '...');
                        if (rows[v] != null) {
                            createZJ(rows[v]);
                        } else {
                            pbar.updateText('全部章节生成HTML完成')
                        }
                    } else {
                        Ext.Msg.alert("错误", result.errorMessage);
                    }
                }
            });
        }
        Ext.Msg.confirm("提示", "确定要生成选中的全部章节页面吗？", function (result) {
            if (result == "yes") {
                Ext.Ajax.request({
                    url: 'data/chapter.aspx?a=allid',
                    success: function (response, opts) {
                        var result = Ext.decode(response.responseText);
                        if (result.success) {
                            rows = result.allid;
                            pbar.reset();
                            pbar.show();
                            createZJ(rows[0])
                        }
                    }
                });
                
            }
        });
    },

    renderChapterList: function (panel) {
        this.getChaptersStore().proxy.extraParams = { cid: panel.comicid };
        this.getChaptersStore().load();
        this.getComicDatasStore().each(function (row) {
            panel.down("button[action=add]").menu.add({
                text: row.get("name"),
                tooltip: row.get("value")
            });
        });
    }
});
